package kr.ac.kaist.vrowser;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import kr.ac.kaist.vrowser.asynctasks.VrowserAsyncTask;
import kr.ac.kaist.vrowser.data.FormElement;
import kr.ac.kaist.vrowser.data.FormElementType;
import kr.ac.kaist.vrowser.data.FormOptionElement;
import kr.ac.kaist.vrowser.data.FormSection;
import kr.ac.kaist.vrowser.data.FormSelectElement;
import kr.ac.kaist.vrowser.data.HTMLDocument;
import kr.ac.kaist.vrowser.data.Link;
import kr.ac.kaist.vrowser.db.models.Bookmark;
import kr.ac.kaist.vrowser.fragments.BookmarkFragment;
import kr.ac.kaist.vrowser.fragments.FormFragment;
import kr.ac.kaist.vrowser.fragments.FormFragment.FormClick;
import kr.ac.kaist.vrowser.fragments.FormSectionFragment;
import kr.ac.kaist.vrowser.fragments.FormSectionFragment.FormElementClick;
import kr.ac.kaist.vrowser.fragments.FormSelectFragment;
import kr.ac.kaist.vrowser.fragments.FormSelectFragment.FormSelectClick;
import kr.ac.kaist.vrowser.fragments.LinkFragment;
import kr.ac.kaist.vrowser.gethtml.GetHTMLInterface;
import kr.ac.kaist.vrowser.getbookmark.GetBookmarkInterface;
import kr.ac.kaist.vrowser.gotofirstpage.GoToFirstPageInterface;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.InputType;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class MainActivity extends VrowserBaseActivity implements
		GetBookmarkInterface, GetHTMLInterface, OnGestureListener,
		OnDoubleTapListener, GoToFirstPageInterface {

	private int linkCount = 1;
	private int formCount = 0;
	private ViewPager pager;
	private DialFragmentPageAdapter pageAdapter;
	private boolean pageRefresh = true;
	private Button invisibleButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		GestureDetector gd = new GestureDetector(this, this);
		gd.setOnDoubleTapListener(this);

		WebView webView = (WebView) this.findViewById(R.id.webView);
		app.getWebController().setWebView(webView, this);
		app.getBookmarkController().setBookmarkInterface(this);

		// LinearLayout rootLayout = (LinearLayout)
		// this.findViewById(R.id.layout);
		invisibleButton = (Button) this.findViewById(R.id.invisibleButton);
		invisibleButton.setFocusableInTouchMode(true);
		invisibleButton.requestFocus();

		pager = (ViewPager) findViewById(R.id.pager);

		try {
			pageAdapter = new DialFragmentPageAdapter(
					this.getSupportFragmentManager());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		pageAdapter.loadBookmark();

		pager.setAdapter(pageAdapter);
		pager.setOnPageChangeListener(new OnPageChangeListener() {

			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}

			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			public void onPageSelected(int position) {
				String msg;
				if (pageAdapter.mode == FragmentMode.Bookmark) {
					app.getTextToSpeech().speak(
							String.format(
									getResources().getString(
											R.string.bookmarkPageSelected),
									position + 1), TextToSpeech.QUEUE_FLUSH,
							null);
					app.getBookmarkController().setCurrentBookmarkPosition(
							position);
				} else {
					if (pageRefresh) {
						pageRefresh = false;
						return;
					}
					if (position >= formCount) {
						msg = String.format(
								getResources().getString(
										R.string.linkPageSelected), position
										- formCount + 1);
					} else {
						msg = String.format(
								getResources().getString(
										R.string.formPageSelected), formCount
										- position);
					}
					if (app.getTextToSpeech() != null)
						app.getTextToSpeech().speak(msg,
								TextToSpeech.QUEUE_FLUSH, null);
				}

			}
		});

		BookmarksAsyncTask task = new BookmarksAsyncTask(this);
		task.execute();
	}

	public enum FragmentMode {
		Page, FormSection, FormSelect, Bookmark
	}

	private class DialFragmentPageAdapter extends FragmentStatePagerAdapter
			implements FormClick, FormElementClick, FormSelectClick {

		FragmentMode mode;

		List<FormSectionFragment> sectionFragments = new ArrayList<FormSectionFragment>();
		List<BookmarkFragment> bookmarkFragments = new ArrayList<BookmarkFragment>();
		List<LinkFragment> linkFragments = new ArrayList<LinkFragment>();
		List<FormFragment> formFragments = new ArrayList<FormFragment>();
		List<FormSelectFragment> selectFragments = new ArrayList<FormSelectFragment>();

		private int getBookmarkButtonNumber(int i, int j) {
			return 6 * i + j;
		}

		public DialFragmentPageAdapter(FragmentManager fm) throws SQLException {
			super(fm);
			makeBookmarkFragments();
		}

		public void resetBookmarkFragments() throws SQLException {
			app.getBookmarkController().refreshLongClickStatus();
			bookmarkFragments.clear();
			makeBookmarkFragments();
		}

		private int getLinkButtonNumber(int i, int j) {
			return 6 * i + j - 2;
		}

		private int getFormButtonNumber(int i, int j) {
			return 6 * i + j;
		}

		// make bookmark fragments
		public void makeBookmarkFragments() throws SQLException {
			List<Bookmark> bookmarks = app.getBookmarkController()
					.getBookmarks();
			int bookmarkCount = (bookmarks.size() - 1) / 6 + 1;
			for (int i = 0; i < bookmarkCount; i++) {
				ArrayList<Bookmark> buttonBookmarks = new ArrayList<Bookmark>();
				for (int j = 0; j < 6; ++j) {
					int bn = getBookmarkButtonNumber(i, j);
					if (bn >= bookmarks.size()) {
						break;
					} else {
						buttonBookmarks.add(bookmarks.get(bn));
					}
				}

				bookmarkFragments.add(BookmarkFragment.newInstance(i,
						buttonBookmarks));
			}

		}

		public void loadBookmark() {
			mode = FragmentMode.Bookmark;
			linkFragments.clear();
			formFragments.clear();

			if (app.getTextToSpeech() != null)
				app.getTextToSpeech().speak(
						getResources().getString(R.string.bookmarkLoad),
						TextToSpeech.QUEUE_FLUSH, null);

			notifyDataSetChanged();

			pager.invalidate();
			pager.setCurrentItem(0);

			final EditText urlEditText = (EditText) activity
					.findViewById(R.id.goURL);
			urlEditText.setText("");
		}

		public void loadUrl(String html) {
			HTMLDocument htmlDoc;
			
			try{
				htmlDoc = app.getWebController().buildHTMLDocument(
					html);
			} catch (Exception e) {
				return;
			}
			mode = FragmentMode.Page;
			linkFragments.clear();
			formFragments.clear();

			ArrayList<Link> links = htmlDoc.links;
			linkCount = ((links.size() + 2 - 1) / 6) + 1;
			int pos = 0;
			for (int i = 0; i < linkCount; ++i) {
				ArrayList<Link> buttonLinks = new ArrayList<Link>();
				for (int j = 0; j < 6; ++j) {
					if (i == 0 && j == 0) {
						buttonLinks
								.add(new Link(getResources().getString(
										R.string.buttonContents),
										"vrowser://contents"));
						continue;
					}
					if (i == 0 && j == 1) {
						buttonLinks.add(new Link(getResources().getString(
								R.string.buttonLinks), "vrowser://links"));
						continue;
					}
					if (getLinkButtonNumber(i, j) >= links.size()) {
						break;
					}
					buttonLinks.add(links.get(getLinkButtonNumber(i, j)));
				}
				linkFragments.add(LinkFragment.newInstance(pos, buttonLinks,
						(GoToFirstPageInterface) activity));
				pos++;
			}

			// Form pages
			ArrayList<FormSection> forms = htmlDoc.forms;
			if (forms.size() == 0)
				formCount = 0;
			else
				formCount = (forms.size() - 1) / 6 + 1;
			for (int i = 0; i < formCount; ++i) {
				ArrayList<FormSection> buttonForms = new ArrayList<FormSection>();
				for (int j = 0; j < 6; ++j) {
					if (getFormButtonNumber(i, j) >= forms.size()) {
						break;
					} else {
						buttonForms.add(forms.get(getFormButtonNumber(i, j)));
					}
				}
				FormFragment formFragment = FormFragment.newInstance(
						buttonForms, (GoToFirstPageInterface) activity);
				formFragment.setFormClick(this);
				formFragments.add(formFragment);
			}

			pageRefresh = true;
			String str = String.format(
					getResources().getString(R.string.pageLoadCompleted),
					htmlDoc.title, linkCount, formCount);
			if (app.getTextToSpeech() != null)
				app.getTextToSpeech()
						.speak(str, TextToSpeech.QUEUE_FLUSH, null);

			notifyDataSetChanged();

			pager.invalidate();
			pager.setCurrentItem(formCount);

			final EditText urlEditText = (EditText) activity
					.findViewById(R.id.goURL);

			String cur_url = app.getWebController().current_url;
			if (cur_url != null && cur_url.length() > 0) {
				urlEditText.setText(cur_url);
			}
		}

		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public Fragment getItem(int position) {
			switch (mode) {
			case FormSelect: {
				Fragment f = selectFragments.get(position);
				System.out.println(f);
				return f;
			}
			case FormSection: {
				Fragment f = sectionFragments.get(position);
				System.out.println(f);
				return f;
			}
			case Bookmark: {
				Fragment f = bookmarkFragments.get(position);
				System.out.println(f);
				return f;
			}
			case Page:
				if (position >= formCount) {
					Fragment f = linkFragments.get(position - formCount);
					System.out.println(f);
					return f;
				} else {
					Fragment f = formFragments.get(formCount - position - 1);
					System.out.println(f);
					return f;
				}
			}
			return null;
		}

		@Override
		public int getCount() {
			switch (mode) {
			case FormSelect:
				return selectFragments.size();
			case FormSection:
				return sectionFragments.size();
			case Bookmark:
				return pageAdapter.bookmarkFragments.size();
			case Page:
				return linkCount + formCount;
			}
			return 0;
		}

		@Override
		public void onFormClick(FormSection formSection) {
			List<FormElement> elements = new ArrayList<FormElement>();

			sectionFragments.clear();
			boolean submit = false;
			List<FormElement> formElements = new ArrayList<FormElement>();
			for (FormElement el : formSection.elements) {
				if (el.type == FormElementType.Submit) {
					submit = true;
					if (el.name == null || el.name.length() == 0) {
						el.name = getString(R.string.formSubmitLabel);
					}
				}
				if (el.type != FormElementType.Hidden) {
					formElements.add(el);
				}
			}

			if (!submit) {
				FormElement submitElement = new FormElement();
				submitElement.name = getResources().getString(
						R.string.formSubmitLabel);
				submitElement.type = FormElementType.Submit;
				formElements.add(submitElement);
			}

			for (int i = 0; i < formElements.size(); ++i) {
				elements.add(formElements.get(i));

				if (i % 6 == 5 || i == formElements.size() - 1) {
					FormSectionFragment sectionFragment = FormSectionFragment
							.newInstance(formSection, elements);
					sectionFragment.setFormElementClick(this);
					elements = new ArrayList<FormElement>();

					sectionFragments.add(sectionFragment);
				}
			}
			mode = FragmentMode.FormSection;

			oldPage = pager.getCurrentItem();

			notifyDataSetChanged();
			pager.setCurrentItem(0);
		}

		private int oldPage;

		@Override
		public void onFormElementClick(final FormElement formElement,
				final FormSectionFragment sectionFragment) {
			InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

			// if login form load saved data
			boolean loadForm = false;
			String formUrl = sectionFragment.formSection.action;
			String name = formElement.name;

			if (formUrl != null && formUrl.contains("login")) {
				loadForm = true;
			}

			switch (formElement.type) {
			case Text:
				sectionFragment.elementLayout.setVisibility(View.VISIBLE);
				sectionFragment.edittext.setVisibility(View.VISIBLE);
				sectionFragment.edittext.requestFocus();

				in.showSoftInput(sectionFragment.edittext, 0);

				if (formElement.value != null) {
					sectionFragment.edittext.setText(formElement.value);
				} else {
					sectionFragment.edittext.setText("");
				}

				if (loadForm) {
					if (name.contains("user") || name.contains("id")
							|| name.contains("name")) {
						String value = "";
						try {
							value = app.getFormController().getForm(name,
									formUrl);
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						if (value.length() > 0) {
							sectionFragment.edittext.setText(value);
						}
					}
				}

				sectionFragment.edittext
						.setOnFocusChangeListener(new OnFocusChangeListener() {

							@Override
							public void onFocusChange(View arg0, boolean focus) {
								if (!focus) {
									formElement.value = sectionFragment.edittext
											.getText().toString();
									sectionFragment.edittext.clearFocus();

									InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
									in.hideSoftInputFromWindow(
											sectionFragment.edittext
													.getApplicationWindowToken(),
											InputMethodManager.HIDE_NOT_ALWAYS);

									invisibleButton.requestFocus();
									sectionFragment.edittext
											.setVisibility(View.INVISIBLE);
									sectionFragment.elementLayout
											.setVisibility(View.INVISIBLE);
									app.getTextToSpeech()
											.speak(String
													.format(getResources()
															.getString(
																	R.string.formTextClose),
															formElement.value),
													TextToSpeech.QUEUE_FLUSH,
													null);
								}
							}

						});
				sectionFragment.edittext
						.setOnEditorActionListener(new OnEditorActionListener() {

							@Override
							public boolean onEditorAction(TextView textView,
									int actionId, KeyEvent event) {
								if (actionId == EditorInfo.IME_NULL
										&& event.getAction() == KeyEvent.ACTION_DOWN) {
									formElement.value = sectionFragment.edittext
											.getText().toString();
									sectionFragment.edittext.clearFocus();
									invisibleButton.requestFocus();

									InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
									in.hideSoftInputFromWindow(
											sectionFragment.edittext
													.getApplicationWindowToken(),
											InputMethodManager.HIDE_NOT_ALWAYS);

									sectionFragment.edittext
											.setVisibility(View.INVISIBLE);
									sectionFragment.elementLayout
											.setVisibility(View.INVISIBLE);
									app.getTextToSpeech()
											.speak(String
													.format(getResources()
															.getString(
																	R.string.formTextClose),
															formElement.value),
													TextToSpeech.QUEUE_FLUSH,
													null);
								}
								return true;
							}

						});
				break;
			case Password:
				sectionFragment.elementLayout.setVisibility(View.VISIBLE);
				sectionFragment.password.setVisibility(View.VISIBLE);
				sectionFragment.password.requestFocus();

				in.showSoftInput(sectionFragment.password, 0);

				if (formElement.value != null) {
					sectionFragment.password.setText(formElement.value);
				} else {
					sectionFragment.password.setText("");
				}

				// load form
				if (loadForm) {
					// Log.i("save form", "load password");
					String pw = "";
					try {
						pw = app.getFormController().getForm(name, formUrl);
						// Log.i("save form", "saved password= "+pw);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (pw.length() > 0) {
						sectionFragment.password.setText(pw);
					}
				}

				sectionFragment.password
						.setOnFocusChangeListener(new OnFocusChangeListener() {

							@Override
							public void onFocusChange(View arg0, boolean focus) {
								if (!focus) {
									formElement.value = sectionFragment.password
											.getText().toString();
									sectionFragment.password.clearFocus();

									InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
									in.hideSoftInputFromWindow(
											sectionFragment.password
													.getApplicationWindowToken(),
											InputMethodManager.HIDE_NOT_ALWAYS);

									invisibleButton.requestFocus();
									sectionFragment.password
											.setVisibility(View.INVISIBLE);
									sectionFragment.elementLayout
											.setVisibility(View.INVISIBLE);
									app.getTextToSpeech()
											.speak(String
													.format(getString(R.string.formPasswordClose),
															formElement.value),
													TextToSpeech.QUEUE_FLUSH,
													null);
								}
							}

						});
				sectionFragment.password
						.setOnEditorActionListener(new OnEditorActionListener() {

							@Override
							public boolean onEditorAction(TextView textView,
									int actionId, KeyEvent event) {
								// if (actionId == EditorInfo.IME_NULL
								// && event.getAction() == KeyEvent.ACTION_DOWN)
								// {
								formElement.value = sectionFragment.password
										.getText().toString();
								sectionFragment.password.clearFocus();
								invisibleButton.requestFocus();

								InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
								in.hideSoftInputFromWindow(
										sectionFragment.password
												.getApplicationWindowToken(),
										InputMethodManager.HIDE_NOT_ALWAYS);

								sectionFragment.password
										.setVisibility(View.INVISIBLE);
								sectionFragment.elementLayout
										.setVisibility(View.INVISIBLE);
								app.getTextToSpeech()
										.speak(String
												.format(getString(R.string.formPasswordClose),
														formElement.value),
												TextToSpeech.QUEUE_FLUSH, null);
								// }
								return true;
							}

						});
				break;
			case TextArea: // FIX ME MULTILINE!
				sectionFragment.elementLayout.setVisibility(View.VISIBLE);
				sectionFragment.textarea.setVisibility(View.VISIBLE);
				sectionFragment.textarea.requestFocus();

				in.showSoftInput(sectionFragment.textarea, 0);

				if (formElement.value != null) {
					sectionFragment.textarea.setText(formElement.value);
				} else {
					sectionFragment.textarea.setText("");
				}
				sectionFragment.textarea
						.setOnFocusChangeListener(new OnFocusChangeListener() {

							@Override
							public void onFocusChange(View arg0, boolean focus) {
								if (!focus) {
									formElement.value = sectionFragment.textarea
											.getText().toString();
									sectionFragment.textarea.clearFocus();

									InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
									in.hideSoftInputFromWindow(
											sectionFragment.textarea
													.getApplicationWindowToken(),
											InputMethodManager.HIDE_NOT_ALWAYS);

									invisibleButton.requestFocus();
									sectionFragment.textarea
											.setVisibility(View.INVISIBLE);
									sectionFragment.elementLayout
											.setVisibility(View.INVISIBLE);
									app.getTextToSpeech()
											.speak(String
													.format(getString(R.string.formTextareaClose),
															formElement.value),
													TextToSpeech.QUEUE_FLUSH,
													null);
								}
							}

						});
				sectionFragment.textarea
						.setOnEditorActionListener(new OnEditorActionListener() {

							@Override
							public boolean onEditorAction(TextView textView,
									int actionId, KeyEvent event) {
								if (actionId == EditorInfo.IME_NULL
										&& event.getAction() == KeyEvent.ACTION_DOWN) {
									formElement.value = sectionFragment.textarea
											.getText().toString();
									sectionFragment.textarea.clearFocus();
									invisibleButton.requestFocus();

									InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
									in.hideSoftInputFromWindow(
											sectionFragment.textarea
													.getApplicationWindowToken(),
											InputMethodManager.HIDE_NOT_ALWAYS);

									sectionFragment.textarea
											.setVisibility(View.INVISIBLE);
									sectionFragment.elementLayout
											.setVisibility(View.INVISIBLE);
									app.getTextToSpeech()
											.speak(String
													.format(getString(R.string.formTextareaClose),
															formElement.value),
													TextToSpeech.QUEUE_FLUSH,
													null);
								}
								return true;
							}
						});
				break;
			case CheckBox:
				formElement.checked = !formElement.checked;
				if (formElement.checked)
					app.getTextToSpeech().speak(
							String.format(getString(R.string.formChecked),
									formElement.name, formElement.value),
							TextToSpeech.QUEUE_FLUSH, null);
				else
					app.getTextToSpeech().speak(
							String.format(getString(R.string.formUnchecked),
									formElement.name, formElement.value),
							TextToSpeech.QUEUE_FLUSH, null);
				break;
			case Select: {
				startSelectFragments((FormSelectElement) formElement);
				break;
			}
			case Return:
				sectionFragment.elementLayout.setVisibility(View.INVISIBLE);
				mode = FragmentMode.Page;
				this.notifyDataSetChanged();
				pager.setCurrentItem(oldPage);
				break;
			case Reset:
				app.getWebController().resetForm(sectionFragment.formSection);
				break;
			case Submit:
				app.getWebController().submitForm(sectionFragment.formSection);
				break;
			default:
				break;
			}
		}

		private int oldFormPage = 0;

		public void startSelectFragments(FormSelectElement selectElement) {
			mode = FragmentMode.FormSelect;
			this.selectFragments.clear();

			int optionsCount = (selectElement.options.size()) / 6 + 1;
			for (int i = 0; i < optionsCount; i++) {
				List<FormOptionElement> buttonOptions = new ArrayList<FormOptionElement>();
				for (int j = 0; j < 6; ++j) {
					int bn = getBookmarkButtonNumber(i, j);
					if (bn >= selectElement.options.size() + 1) {
						break;
					} else if (i == 0 && j == 0) {
						buttonOptions.add(null);
					} else {
						buttonOptions.add(selectElement.options.get(bn - 1));
					}
				}

				FormSelectFragment f = FormSelectFragment.newInstance(
						buttonOptions, selectElement);
				f.setFormSelectClick(this);

				selectFragments.add(f);
			}

			oldFormPage = pager.getCurrentItem();

			this.notifyDataSetChanged();
			pager.setCurrentItem(0);
		}

		@Override
		public void onFormSelectClick(FormOptionElement option,
				FormSelectElement selectElement) {
			if (option == null) {
				app.getTextToSpeech().speak(
						getString(R.string.formReturnMessage),
						TextToSpeech.QUEUE_FLUSH, null);
				mode = FragmentMode.FormSection;
				this.notifyDataSetChanged();
				pager.setCurrentItem(oldFormPage);
				return;
			}
			for (FormOptionElement optionElement : selectElement.options) {
				optionElement.checked = false;
			}
			option.checked = true;

			app.getTextToSpeech().speak(
					String.format(getString(R.string.formChecked),
							selectElement.name, option.label),
					TextToSpeech.QUEUE_FLUSH, null);
		}
	}

	private class BookmarksAsyncTask extends VrowserAsyncTask<Void> {

		public BookmarksAsyncTask(VrowserBaseActivity activity) {
			super(activity);
		}

		@Override
		protected void afterExecute(Void result) throws Exception {
			final EditText urlEditText = (EditText) _activity
					.findViewById(R.id.goURL);
			final ImageButton homeButton = (ImageButton) _activity
					.findViewById(R.id.goHome);
			final ImageButton forwardButton = (ImageButton) _activity
					.findViewById(R.id.goForward);
			final ImageButton backButton = (ImageButton) _activity
					.findViewById(R.id.goBack);

			urlEditText.setInputType(InputType.TYPE_NULL);
			
			urlEditText.setOnClickListener(new OnClickListener() {

				public void onClick(View view) {
					Intent editUrlIntent = new Intent(_activity,
							UrlEditActivity.class);
					startActivity(editUrlIntent);
				}

			});

			/*
			urlEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) {
						Intent editUrlIntent = new Intent(_activity,
								UrlEditActivity.class);
						startActivity(editUrlIntent);
					}
				}
			});
			*/

			// add bookmark
			urlEditText.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					String url = app.getWebController().current_url;
					String title = app.getWebController().current_title;
					try {
						app.getTextToSpeech().speak(
								String.format(getString(R.string.bookmarkAdd),
										title), TextToSpeech.QUEUE_FLUSH, null);
						app.getBookmarkController().addBookmark(title, url,
								false);
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					return true;
				}

			});

			homeButton.setOnClickListener(new OnClickListener() {
				public void onClick(View view) {
					app.getTextToSpeech().speak(getString(R.string.buttonHome),
							TextToSpeech.QUEUE_FLUSH, null);
					//app.getWebController().resetBrowsingHistory();
					app.getWebController().goHome();
					pageAdapter.loadBookmark();
				}
			});

			forwardButton.setOnClickListener(new OnClickListener() {
				public void onClick(View view) {
					String forward = app.getWebController().goForward();
					if (forward == null) {
						app.getTextToSpeech().speak(
								getString(R.string.goForwardEmpty),
								TextToSpeech.QUEUE_FLUSH, null);
					} else if (forward.equals("home")){
						pageAdapter.loadBookmark();
						app.getTextToSpeech().speak(getString(R.string.homeDescription), TextToSpeech.QUEUE_FLUSH, null);
					}
					else {
						app.getTextToSpeech().speak(
								String.format(
										getString(R.string.goForwardMessage),
										forward), TextToSpeech.QUEUE_FLUSH,
								null);
						urlEditText.setText(forward);
					}
				}
			});

			backButton.setOnClickListener(new OnClickListener() {
				public void onClick(View view) {
					String back = app.getWebController().goBack();
					if (back == null) {
						if (pageAdapter.mode == FragmentMode.Bookmark) {
							app.getTextToSpeech().speak(
									getString(R.string.goBackEmpty),
									TextToSpeech.QUEUE_FLUSH, null);
						} else {
							// change here
							pageAdapter.loadBookmark();
						}
					} else if (back.equals("home")){
						pageAdapter.loadBookmark();
						app.getTextToSpeech().speak(getString(R.string.homeDescription), TextToSpeech.QUEUE_FLUSH, null);
					} else {
						app.getTextToSpeech()
								.speak(String
										.format(getString(R.string.goBackMessage),
												back),
										TextToSpeech.QUEUE_FLUSH, null);
						urlEditText.setText(back);
					}
				}
			});

		}

		@Override
		protected Void executeInBackground() throws Exception {
			app.getBookmarkController().getBookmarks();
			return null;
		}

		@Override
		protected void beforeExecute() throws Exception {

		}

	}

	// for calling from BookmarkFragment
	@Override
	public void onBookmarkChange() {
		try {
			pageAdapter.resetBookmarkFragments();
			pageAdapter.notifyDataSetChanged();
			pager.invalidate();
			pager.setCurrentItem(app.getBookmarkController()
					.getCurrentBookmarkPosition());

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onGetHTML(String html) {
		// Log.i(checkHtml, html);
		LinearLayout layout = (LinearLayout) this.findViewById(R.id.layout);
		layout.clearAnimation();
		layout.removeViewAt(layout.getChildCount()-1);
		int child = layout.getChildCount();
		for (int i=0; i<child; i++) {
			layout.getChildAt(i).setVisibility(View.VISIBLE);
		}
		
		pageAdapter.loadUrl(html);
	}
	
	@Override
	public boolean onDoubleTap(MotionEvent arg0) {
		// android.util.Log.i("","double tap!");
		return true;
	}

	@Override
	public boolean onDoubleTapEvent(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onSingleTapConfirmed(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onDown(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent arg0) {
		// TODO Auto-generated method stub

		return false;
	}

	@Override
	public void goToFirstPage(boolean up) {
		if (up) {
			// to form 1 page
			pager.setCurrentItem(0);
		} else {
			// to link 1 page
			pager.setCurrentItem(formCount);
		}
	}
	
	@Override
	protected void onStop() {
		super.onStop();
	}
	
	@Override
	protected void onDestroy(){
		super.onDestroy();
		//app.getWebController().resetBrowsingHistory();
	}

}
